package com.bsd.xxyp.rdlock.context;

import com.bsd.xxyp.rdlock.entity.LockInfo;
import com.bsd.xxyp.rdlock.exception.RdLockException;

import java.util.LinkedList;

/**
 * @author ：wangcheng
 * @date 2022/12/31
 **/
public class TemporaryVariableContext {

    private static final InheritableThreadLocal<LinkedList<LockInfo>> TEMP = new InheritableThreadLocal<>();

    public void pushTempVariable(LockInfo lockInfo) {
        LinkedList deque = TEMP.get();
        if (deque == null) {
            deque = new LinkedList();
            TEMP.set(deque);
        }
        deque.push(lockInfo);
    }

    public LockInfo popTemVariable() {
        LinkedList<LockInfo> lockInfos = TEMP.get();
        if (lockInfos == null) {
            throw new RdLockException("rdLock error: 当前线程threadLocal变量未初始化");
        }
        LockInfo pop = lockInfos.pop();
        if (lockInfos.isEmpty()) {
            TEMP.remove();
        }
        return pop;
    }

}
